import { native, sys, view } from "cc";
import { NATIVE, WECHAT } from "cc/env";
// import { msgac } from "../game/data/msgac";
// import { eventManager } from "../game/manager/eventManager";
import { wechat } from "../Network/Wechat";
import { EType, IPos, WXCustomAd } from "../UI/WXCustomAd";
import { tyqSDK } from "../Managers/TyqSDK";
import { tyqSDKConfig } from "../Constans/TyqSDKConfig";

/**渠道 */
export enum Channel {
    /**默认 浏览器*/
    DEFAULT = 0,
    /**微信小游戏 */
    WECHAT = 1,
    ANDROID,
    IOS,
    ANDROID_233,
    ANDROID_4399,
    H5_4399,
}

class TyqAdManager {

    private static _instance: TyqAdManager;
    public static get instance(): TyqAdManager {
        if (!this._instance) {
            this._instance = new TyqAdManager();
        }
        return this._instance;
    }

    private channel: Channel = Channel.DEFAULT;





    // 默认原生广告各个类型的尺寸
    public customAdSizeObj: any = {
        // 矩阵 行数：5
        rect: {
            width: 360,
            height: 506
        },
        // 横向 尺寸：80%  默认数：5
        horizontal: {
            width: 288,
            height: 90
        },
        // 竖向 尺寸：90%  默认数：5
        vertical: {
            width: 62,
            height: 388
        },
        // 单个格子 尺寸：90%
        grid: {
            width: 68,
            height: 102
        }
    };

    // 当前显示广告的类型
    private adShowType: string;
    // banner广告是否正在显示中
    private bannerAdShowing: boolean = false;
    // banner广告显示接口调用次数
    private showBannerCount = 0;

    private shareTime = 0
    private shareListenerSuccess = null
    private shareListenerFail = null

    private openID = ""

    private strategy = 1

    public videoCallBack: Function = () => { };
    public videoCallBackFail: Function = () => { };

    private shareopenID = ""

    constructor() {
        if (sys.platform == sys.Platform.WECHAT_GAME) {
            this.channel = Channel.WECHAT;

            let windowSize = view.getVisibleSize();
            if (windowSize.width / windowSize.height > 720 / 1440) {
                wechat.bannerSize = {width:300, height:120}
            } 

        } else {
            this.channel = Channel.DEFAULT;
        }
        if (NATIVE) {
            this.channel = Channel.ANDROID_4399;
        }
    }

    public getEnterUrlQuery() {
        if (this.channel == Channel.WECHAT) {
            // 冷启动 wx.getLaunchOptionsSync()
            // 冷启动和热启动 wx.getEnterOptionsSync()
            if (wx.getEnterOptionsSync) {
                let options = wx.getEnterOptionsSync();
                //    console.log("options", options)
                if (options && options.query) {
                    //  console.log("options.query", options.query.toString())
                    let openID = options.query.shareGameSync
                    //    console.log("login openID = ", openID)
                    if (openID) {
                        // this.reportShareBehavior(6, 1, openID)
                        this.shareopenID = openID
                        tyqSDK.eventSendCustomEvent("参与激励托管分享成功进来的玩家")
                    }
                    return options.query;
                }
            }
        }
        return null;
    }

    public showAppMessage() {
        this.shareTime = new Date().getTime()
        console.log("this.openID = ", this.openID)
        wechat.shareAppMessage("挑战未知敌人，化身特工", "", "shareGameSync=" + this.openID)
    }

    public getOpenID() {
        //只能在服务端请求
      
    }

    public getChannel() {
        return this.channel;
    }

    public initAdIds() {

        if (this.channel == Channel.WECHAT) {
            // 显示当前页面的转发按钮
            // "shareAppMessage"表示“发送给朋友”按钮，"shareTimeline"表示“分享到朋友圈”按钮
            wx.showShareMenu({
                withShareTicket: true,
                menus: ['shareAppMessage', 'shareTimeline']
            });

            wx.onHide(this.wxOnHide.bind(this));
            wx.onShow(this.wxOnShow.bind(this));

            // banner广告参数
            let bannerIds = tyqSDK.getSwitchValue(tyqSDKConfig.paramsKeys.tyq_ad_banners);
            if (bannerIds) {
                wechat._bannerAdUnitId = bannerIds.split(";");
            } else {
                tyqSDK.log("未配置banner广告参数");
            }

            // 插屏广告参数
            let interstitialIds = tyqSDK.getSwitchValue(tyqSDKConfig.paramsKeys.tyq_ad_interstitial);
            if (interstitialIds) {
                wechat._interstitialAdUnitId = interstitialIds.split(";");
            } else {
                tyqSDK.log("未配置banner广告参数");
            }

            // 原生广告参数
            let customRectIds = tyqSDK.getSwitchValue(tyqSDKConfig.paramsKeys.tyq_ad_custom_rect);
            if (customRectIds) {
                WXCustomAd._customc_rect_adunit = customRectIds.split(";");
                //  console.log(" WXCustomAd._customc_rect_adunit = ",WXCustomAd._customc_rect_adunit)
            } else {
                tyqSDK.log("未配置原生矩阵广告参数");
            }
            let customVIds = tyqSDK.getSwitchValue(tyqSDKConfig.paramsKeys.tyq_ad_custom_v);
            if (customVIds) {
                WXCustomAd._customc_v_adunit = customVIds.split(";");
            } else {
                tyqSDK.log("未配置原生垂直广告参数");
            }
            let customHIds = tyqSDK.getSwitchValue(tyqSDKConfig.paramsKeys.tyq_ad_custom_h);
            if (customHIds) {
                WXCustomAd._customc_h_adunit = customHIds.split(";");
            } else {
                tyqSDK.log("未配置原生水平广告参数");
            }

            // 激励视频广告参数
            let rewardedIds = tyqSDK.getSwitchValue(tyqSDKConfig.paramsKeys.tyq_ad_rewarded);
            if (rewardedIds) {
                wechat._rewardedVideoAdUnitId = rewardedIds.split(";");
            } else {
                tyqSDK.log("未配置激励视频广告参数");
            }

            // 预加载广告
            // banner广告必须要预加载后才能使用
            wechat.preLoadBanner();

            // 为了减少初始化卡顿时间，激励视频广告可以不预加载
            wechat.createRewardedVideoAd();

            // 为了减少初始化卡顿时间，插屏广告可以不预加载
            // wechat.createInterstitialAd();
        } else if (this.channel == Channel.ANDROID_233 || this.channel == Channel.ANDROID_4399) {
            //  if (NATIVE) {
            console.log(" NATIVE android 平台 initAdIds ")
            
            window.rewardedVideoAdCallBack = (res: any) => {
                //EventHelper.DispatchEvent("showTips", "获得奖励");
                console.log("AD_DEMO rewardedVideoAdCallBack ", res)
                // eventManager.send(msgac.showNotice, " 发放视频奖励 ");
                if (this.videoCallBack) {
                    this.videoCallBack()
                }
            }

            window.rewardedVideoAdFailCallBack = (res: any) => {
                //EventHelper.DispatchEvent("showTips", "获得奖励");
                console.log("AD_DEMO rewardedVideoAdCallBack ", res)
                //    eventManager.send(msgac.showNotice, " 视频奖励 失败");
                if (this.videoCallBackFail) {
                    this.videoCallBackFail()
                }
            }
            //  jsb.reflection.callStaticMethod("org/cocos2dx/javascript/AppActivity", "RewardVideoShow", "(Ljava/lang/String;)V", "展示广告");
            return
            // }
        }
    }

    public wxOnHide(res?) {
        // tyqSDK.log("wx onHide:", res, this.adShowType);
        if (!res) {
            return;
        }

        let mode = res.mode;
        let action = res.targetAction;
        let pagePath = res.targetPagePath;

        // 8：跳转到小游戏内部页面WCCanvasPageViewController
        // 9：跳转到其他微信小游戏
        // 10：跳转到一个链接
        let actions = [8, 9, 10];
        if (actions.indexOf(action) == -1) {
            // 不感兴趣的跳转，直接返回，比如：右上角的圆点或者home键最小化
            return;
        }

        if (this.adShowType) {
            // 已判断到的广告类型，直接使用
            tyqSDK.adClickUpload(this.adShowType, mode, action, pagePath);
            return;
        }

        // 要判断出是banner或者原生广告点击
        if (action == 9) {
            // 跳转其他微信小游戏
            tyqSDK.adClickUpload(tyqSDKConfig.adShowTypes.bannerAndCustomAd, mode, action, pagePath);
            return;
        }
        if (pagePath) {
            // 跳转内部页或者广告链接
            if (pagePath == "WCCanvasPageViewController"
                || pagePath.indexOf("ad.weixin.qq.com") != -1
                || pagePath.indexOf("ad_biz_info") != -1
                || pagePath.indexOf("weixinadkey") != -1
            ) {
                tyqSDK.adClickUpload(tyqSDKConfig.adShowTypes.bannerAndCustomAd, mode, action, pagePath);
            }
            return;
        }

    }

    public wxOnShow(res?) {
        console.log("wx onShow:", res);
        if (this.shareTime > 0 && (new Date().getTime()) - this.shareTime >= 2000) {
            this.shareListenerSuccess && this.shareListenerSuccess()
        } else {
            this.reportShareBehavior(5, this.strategy, 1)
            this.shareListenerFail && this.shareListenerFail()
        }
        this.shareListenerFail = null
        this.shareListenerSuccess = null
        this.shareTime = 0
    }

    /**
     * 显示底部banner轮播广告
     * @param time 轮播间隔时间，单位：毫秒，默认5秒 
     */
    public showBannerAd(time?: number) {
        this.showBannerCount++;

        if (this.channel == Channel.WECHAT) {
            if (this.bannerAdShowing) {
                return true;
            }
            if (!time) {
                time = 5000;
            }
            wechat.showBannerTurns(time);
            this.bannerAdShowing = true;
        } else if (this.channel == Channel.ANDROID_4399) {
            native.reflection.callStaticMethod("com/cocos/game/SdkUtil4399", "showBanner", "(Ljava/lang/String;)Z", "展示banner广告")
        }
    }
    /**
     * 隐藏banner广告
     */
    public hideBannerAd(isForce?: boolean) {
        this.showBannerCount--;
        if (isForce) {
            this.showBannerCount = 0;
        }
        if (this.showBannerCount > 0) {
            return;
        }
        if (this.channel == Channel.WECHAT) {
            wechat.hideBannerAd();
            this.bannerAdShowing = false;
        } else if (this.channel == Channel.ANDROID_4399) {
            native.reflection.callStaticMethod("com/cocos/game/SdkUtil4399", "hideBanner", "(Ljava/lang/String;)Z", "隐藏banner广告")
        }
    }
    /**
     * banner广告是否正在显示中
     */
    public isBannerAdShowing(): boolean {
        return this.bannerAdShowing;
    }

    /**
     * 显示插屏广告
     */
    public showInterstitialAd() {
        if (this.channel == Channel.WECHAT) {
            wechat.showInterstitialAd(() => {
                // 关闭或者发生错误
                this.adShowType = "";
            }, () => {
                // 成功展示
                this.adShowType = tyqSDKConfig.adShowTypes.interstitialAd;
            });
        } else if (this.channel == Channel.ANDROID_233) {
            this.showFullRewarded()
            // native.reflection.callStaticMethod("com/cocos/game/MetaAdApiUtil", "showInterstitialAd", "(Ljava/lang/String;)Z", "展示插屏广告")
        } else if (this.channel == Channel.ANDROID_4399) {
            native.reflection.callStaticMethod("com/cocos/game/SdkUtil4399", "InterstitialShow", "(Ljava/lang/String;)Z", "展示插屏广告")
        }
    }

    private _delayTime = 0

    public showDelayFullVideo() {
        if (this.channel == Channel.ANDROID_233) {
            let time = new Date().getTime()
            // console.log("time - this._delayTime = ",time - this._delayTime)
            if (time - this._delayTime >= 120000) {
                this.showFullRewarded()
                this._delayTime = time
            }
        }
    }

    public showDelayInterstitialAd() {
        if (this.channel == Channel.ANDROID_4399) {
            if (this._delayTime <= 0) {
                this._delayTime = new Date().getTime()
                return
            }
            let time = new Date().getTime()
            if (time - this._delayTime >= 200000) {
                this.showInterstitialAd()
                this._delayTime = time
            }
        }
    }

    /**
     * 显示原生矩阵广告
     */
    public showCustomRectCenterAd(failcb = null) {
        if (this.channel == Channel.WECHAT) {
            //  console.log("showCustomRectCenterAd")
            WXCustomAd.createCustomAd("default_custom_ad_rect", EType.rect, {
                centerX: 0,
                centerY: 0
            }, this.customAdSizeObj.rect, null, failcb);
        }
    }
    /**
     * 隐藏原生矩阵广告
     */
    public hideCustomRectCenterAd() {
        if (this.channel == Channel.WECHAT) {
            WXCustomAd.hideCustomAd("default_custom_ad_rect");
        }
    }

    /**
     * 显示原生垂直广告，显示在左右两边
     */
    public showCustomVerticalLeftRightAd() {
        if (this.channel == Channel.WECHAT) {
            WXCustomAd.createCustomAd("default_custom_ad_v_left", EType.vertical, {
                left: 0
            }, this.customAdSizeObj.vertical);
            WXCustomAd.createCustomAd("default_custom_ad_v_right", EType.vertical, {
                right: 0
            }, this.customAdSizeObj.vertical);
        }
    }
    /**
     * 隐藏原生垂直广告
     */
    public hideCustomVerticalLeftRightAd() {
        if (this.channel == Channel.WECHAT) {
            WXCustomAd.hideCustomAd("default_custom_ad_v_left");
            WXCustomAd.hideCustomAd("default_custom_ad_v_right");
        }
    }

    /**
     * 显示原生水平广告，显示在顶部
     */
    public showCustomHorizontalTopAd() {
        if (this.channel == Channel.WECHAT) {
            WXCustomAd.createCustomAd("default_custom_ad_h", EType.horizontal, {
                top: 0
            }, this.customAdSizeObj.horizontal);
        }
    }
    /**
    * 隐藏原生水平广告
    */
    public hideCustomHorizontalTopAd() {
        if (this.channel == Channel.WECHAT) {
            WXCustomAd.hideCustomAd("default_custom_ad_h");
        }
    }

    /**
     * 通用显示原生广告接口
     * @param flag 标识 
     * @param type 类型
     * @param pos 位置信息
     * @param adSize 尺寸
     * @param adId 广告id
     * @param failcb 失败回调
     */
    public showCustomAd(flag: string, type: EType, pos: IPos, adSize: { width: number, height: number }, adId?: any, failcb?: Function) {
        if (this.channel == Channel.WECHAT) {
            WXCustomAd.createCustomAd(flag, type, pos, adSize, adId, failcb);
        }
    }
    /**
     * 根据创建标识隐藏原生广告
     * @param flag
     */
    public hideCustomAd(flag: string) {
        if (this.channel == Channel.WECHAT) {
            WXCustomAd.hideCustomAd(flag);
        }
    }

    /**
     * 隐藏所有原生广告
     */
    public hideCustomAllAd() {
        if (this.channel == Channel.WECHAT) {
            WXCustomAd.hideAllAd();
        }
    }


    public showFullRewarded() {
        if (this.channel == Channel.ANDROID_233) {
            // successCb && successCb()
            console.log("showFullRewarded")
            native.reflection.callStaticMethod("com/cocos/game/MetaAdApiUtil", "ShowFullRewardVideoShow", "(Ljava/lang/String;)Z", "展示全屏视频广告")
            return
        }
    }

    public reportShareBehavior(operation, strategy = 1, currentShow = null) {

        if (tyqSDKConfig.isOpenBeHavior) {
            if (this.shareopenID != "") {
                wechat.reportShareBehavior({ operation: 6, strategy: 1, inviteUser: this.shareopenID })
                this.shareopenID = ""
            }

            wechat.reportShareBehavior({ operation: operation, strategy: strategy, currentShow: currentShow })
        }
    }

    /**
     * 显示激励视频广告
     */
    public showRewardedAd(successCb?: Function, failCb?: Function, forceVideo = false) {
        this.strategy = 1
        if (tyqSDKConfig.isOpenBeHavior && this.channel == Channel.WECHAT) {
            if (wechat.isShareBehavior()) {
                if (!forceVideo) {
                    tyqAdManager.showAppMessage()
                    this.shareListenerSuccess = successCb
                    this.shareListenerFail = failCb
                    wechat.reportShareBehavior({ operation: 2, strategy: 1, currentShow: 1 })
                    return
                } else {
                    this.strategy = 0
                    wechat.reportShareBehavior({ operation: 2, strategy: 0, currentShow: 0 })
                }
            } else {
                wechat.reportShareBehavior({ operation: 2, strategy: 1, currentShow: 0 })
            }
        }

        if (tyqSDKConfig.isCloseAd) {
            successCb && successCb()
            return
        }

        if (this.channel == Channel.ANDROID_233) {
            this.videoCallBack = successCb
            this.videoCallBackFail = failCb
            // console.log(" NATIVE android 平台 ")
            if (!native.reflection.callStaticMethod("com/cocos/game/MetaAdApiUtil", "RewardVideoShow", "(Ljava/lang/String;)Z", "展示广告")) {
                failCb && failCb();
            }
            return
        }
        if (this.channel == Channel.ANDROID_4399) {
            this.videoCallBack = successCb
            this.videoCallBackFail = failCb
            console.log(" NATIVE android 平台 com/cocos/game/SdkUtil4399")
            if (!native.reflection.callStaticMethod("com/cocos/game/SdkUtil4399", "RewardVideoShow", "(Ljava/lang/String;)Z", "展示广告")) {
                failCb && failCb();
            }
            return
        }

        if (this.channel == Channel.WECHAT) {
            wechat.showRewardVideoAd(() => {
                this.adShowType = tyqSDKConfig.adShowTypes.rewardedAd;
            }).then((isSuccess) => {
                this.adShowType = "";
                if (isSuccess) {
                    if (successCb) {
                        successCb();
                    }
                } else {
                    this.reportShareBehavior(5, this.strategy, 0)
                    if (failCb) {
                        failCb(2);
                    }
                }
            }, () => {
                this.adShowType = "";
                this.reportShareBehavior(5, this.strategy, 0)
                if (failCb) {
                    failCb(0);
                }
            });
        }
    }


}

export const tyqAdManager = TyqAdManager.instance;
